<template>
    <main class="main-page" id="">
        <section class="page-section mb-3">
            <div class="container-fluid">
                <div class="grid justify-content-between align-items-center">
                    <div class="col">
                        <div class="flex align-items-center gap-2">
                            <i class="pi pi-list text-primary text-2xl"></i>
                            <div class="text-2xl text-primary font-bold">
                                系统监控 - 日志审计
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <section class="page-section">
            <div class="container-fluid">
                <div class="grid">
                    <div class="col comp-grid">
                        <Card class="mb-3">
                            <template #title>
                                <div class="flex align-items-center gap-2">
                                    <i class="pi pi-search text-primary"></i>
                                    <span>日志查询</span>
                                </div>
                            </template>
                            <template #content>
                                <div class="flex align-items-center gap-3">
                                    <div class="flex align-items-center gap-2 flex-1">
                                        <span class="text-500">开始时间：</span>
                                        <Calendar v-model="startDate" :showIcon="true" :showButtonBar="true" 
                                            dateFormat="yy-mm-dd" timeFormat="HH:mm:ss" :showTime="true" :showSeconds="true"
                                            placeholder="选择开始时间" class="w-full" />
                                    </div>
                                    <div class="flex align-items-center gap-2 flex-1">
                                        <span class="text-500">结束时间：</span>
                                        <Calendar v-model="endDate" :showIcon="true" :showButtonBar="true" 
                                            dateFormat="yy-mm-dd" timeFormat="HH:mm:ss" :showTime="true" :showSeconds="true"
                                            placeholder="选择结束时间" class="w-full" />
                                    </div>
                                    <Button icon="pi pi-search" label="查询" @click="searchByDate" class="p-button-primary" />
                                </div>
                            </template>
                        </Card>

                        <Card>
                            <template #title>
                                <div class="flex align-items-center gap-2">
                                    <i class="pi pi-table text-primary"></i>
                                    <span>日志审计表</span>
                                </div>
                            </template>
                            <template #content>
                                <DataTable :value="records" class="p-datatable-sm" :stripedRows="true" :showGridlines="false" 
                                    :rowHover="true" responsiveLayout="stack" :loading="loading"
                                    :paginator="true" :rows="pageSize" :totalRecords="totalRecords"
                                    v-model:first="first" @page="onPage">
                                    <template #empty>
                                        <div class="text-center p-3">
                                            <i class="pi pi-inbox text-500 text-2xl mb-2"></i>
                                            <div class="text-500">暂无数据</div>
                                        </div>
                                    </template>
                                    <Column field="timestamp" header="时间">
                                        <template #body="{ data }">
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-clock text-500"></i>
                                                <span class="text-primary">{{ formatDateTime(data.timestamp) }}</span>
                                            </div>
                                        </template>
                                    </Column>
                                    <Column field="user_id" header="执行人">
                                        <template #body="{ data }">
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-user text-500"></i>
                                                <span class="text-primary">{{ data.user_id || '-' }}</span>
                                            </div>
                                        </template>
                                    </Column>
                                    <Column field="action" header="操作类型">
                                        <template #body="{ data }">
                                            <div class="flex align-items-center gap-2">
                                                <i class="pi pi-tag text-500"></i>
                                                <Tag :value="getActionType(data.action)" 
                                                    :severity="getActionSeverity(data.action)"
                                                    class="mr-2" />
                                            </div>
                                        </template>
                                    </Column>
                                    <Column field="details" header="操作详情">
                                        <template #body="{ data }">
                                            <Button icon="pi pi-eye" @click="showDetails(data)" 
                                                class="p-button-text p-button-rounded p-button-primary" />
                                        </template>
                                    </Column>
                                </DataTable>

                                <Dialog v-model:visible="showDetailsDialog" modal header="操作详情" :style="{ width: '50vw' }">
                                    <div class="grid">
                                        <div class="col-12">
                                            <div class="field">
                                                <label class="font-bold">时间：</label>
                                                <div class="flex align-items-center gap-2 mt-1">
                                                    <i class="pi pi-clock text-500"></i>
                                                    <span class="text-primary">{{ selectedRecord ? formatDateTime(selectedRecord.timestamp) : '' }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="field">
                                                <label class="font-bold">执行人：</label>
                                                <div class="flex align-items-center gap-2 mt-1">
                                                    <i class="pi pi-user text-500"></i>
                                                    <span class="text-primary">{{ selectedRecord ? (selectedRecord.user_id || '-') : '' }}</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="col-12">
                                            <div class="field">
                                                <label class="font-bold">操作类型：</label>
                                                <div class="flex align-items-center gap-2 mt-1">
                                                    <i class="pi pi-tag text-500"></i>
                                                    <Tag :value="selectedRecord ? getActionType(selectedRecord.action) : ''" 
                                                        :severity="selectedRecord ? getActionSeverity(selectedRecord.action) : 'info'"
                                                        class="mr-2" />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </Dialog>

                                <div class="flex justify-content-end mt-3">
                                    <Button label="导出CSV" icon="pi pi-download" @click="exportCSV" class="p-button-primary" />
                                </div>
                            </template>
                        </Card>
                    </div>
                </div>
            </div>
        </section>
    </main>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useToast } from 'primevue/usetoast';
import { useApp } from 'src/composables/app.js';
import { useAuth } from 'src/composables/auth';
import Dialog from 'primevue/dialog';
import Card from 'primevue/card';
import Tag from 'primevue/tag';

const startDate = ref(null);
const endDate = ref(null);
const toast = useToast();
const records = ref([]);
const app = useApp();
const auth = useAuth();
const API_BASE_URL = process.env.VUE_APP_API_PATH || 'http://localhost:8060/api/';
const loading = ref(false);
const totalRecords = ref(0);
const pageSize = ref(20);
const first = ref(0);
const currentPage = ref(1);
const showDetailsDialog = ref(false);
const selectedRecord = ref(null);

onMounted(() => {
    const pageTitle = "系统监控 - 日志审计";
    app.setPageTitle(pageTitle);
    loadRecords();
});

async function loadRecords() {
    try {
        loading.value = true;
        const response = await fetch(`${API_BASE_URL}audits/index?page=${currentPage.value}&limit=${pageSize.value}`, {
            headers: {
                'Authorization': `Bearer ${auth.store.getLoginToken()}`
            }
        });
        if (response.ok) {
            const data = await response.json();
            records.value = data.records || [];
            totalRecords.value = data.total || 0;
        }
    } catch (error) {
        console.error('Error loading records:', error);
        toast.add({severity:'error', summary: '错误', detail: '加载记录失败', life: 3000});
    } finally {
        loading.value = false;
    }
}

function onPage(event) {
    first.value = event.first;
    currentPage.value = event.page + 1;
    if (startDate.value && endDate.value) {
        searchByDate();
    } else {
        loadRecords();
    }
}

function formatDateTime(dateTime) {
    if (!dateTime) return '';
    return new Date(dateTime).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    });
}

function getUserName(userId) {
    if (!userId) return '系统自动操作';
    // TODO: 从用户服务获取用户名
    return userId;
}

function getActionType(action) {
    const actionTypes = {
        'login': '登录',
        'add': '新增',
        'edit': '编辑',
        'delete': '删除'
    };
    return actionTypes[action] || action;
}

function getActionSeverity(action) {
    const severityMap = {
        'login': 'success',
        'add': 'info',
        'edit': 'warning',
        'delete': 'danger'
    };
    return severityMap[action] || 'info';
}

function getOperationDetails(data) {
    let details = '';
    switch(data.action) {
        case 'login':
            details = `用户登录系统`;
            break;
        case 'add':
            details = `新增用户 ${data.new_values ? JSON.parse(data.new_values).username : ''}`;
            break;
        case 'edit':
            details = `编辑用户 ${data.old_values ? JSON.parse(data.old_values).username : ''}`;
            break;
        case 'delete':
            details = `删除用户 ${data.old_values ? JSON.parse(data.old_values).username : ''}`;
            break;
        default:
            details = data.action;
    }
    return details;
}

async function searchByDate() {
    if (!startDate.value || !endDate.value) {
        toast.add({severity:'warn', summary: '提示', detail: '请选择开始时间和结束时间', life: 3000});
        return;
    }
    try {
        loading.value = true;
        const response = await fetch(`${API_BASE_URL}audits/index?startDate=${startDate.value.toISOString()}&endDate=${endDate.value.toISOString()}&page=${currentPage.value}&limit=${pageSize.value}`, {
            headers: {
                'Authorization': `Bearer ${auth.store.getLoginToken()}`
            }
        });
        if (response.ok) {
            const data = await response.json();
            records.value = data.records || [];
            totalRecords.value = data.total || 0;
        }
    } catch (error) {
        console.error('Error searching records:', error);
        toast.add({severity:'error', summary: '错误', detail: '搜索记录失败', life: 3000});
    } finally {
        loading.value = false;
    }
}

function exportCSV() {
    if (!records.value.length) {
        toast.add({severity:'warn', summary: '提示', detail: '没有可导出的数据', life: 3000});
        return;
    }
    
    const csvContent = [
        ['时间', '执行人', '操作类型', '操作详情'].join(','),
        ...records.value.map(record => {
            const date = new Date(record.timestamp);
            const formattedDate = date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit',
                hour12: false
            });
            return [
                formattedDate,
                record.user_id || '系统自动操作',
                getActionType(record.action),
                getOperationDetails(record)
            ].join(',');
        })
    ].join('\n');
    
    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = `audit_log_${new Date().toISOString().split('T')[0]}.csv`;
    link.click();
}

function showDetails(record) {
    selectedRecord.value = record;
    showDetailsDialog.value = true;
}
</script>

<style scoped>
.main-page {
    padding: 1rem;
}

.field {
    margin-bottom: 1rem;
}

:deep(.p-datatable .p-datatable-thead > tr > th) {
    background: var(--surface-section);
    color: var(--text-color);
    font-weight: 600;
}

:deep(.p-datatable .p-datatable-tbody > tr > td) {
    padding: 0.75rem 1rem;
}

:deep(.p-datatable .p-datatable-tbody > tr:hover) {
    background: var(--surface-hover);
}
</style> 